import React, { useRef, createContext, useContext } from 'react';
import { proxy } from '@umijs/max';
import { merge } from 'lodash-es';

const initState = {
  // 画布实例
  flowInstance: null,

  /**
   * Node 节点属性
   * https://reactflow.dev/docs/api/nodes/node-options/#typescript
   */
  nodeProps: {
    // label: undefined,
  },

  /**
   * Edge 默认属性参考
   * https://reactflow.dev/docs/api/edges/edge-options/#edge
   */
  edgeProps:  {
    // label: undefined,
    type: 'smoothstep',
    animated: false,
    markerEnd: {
      type: 'arrow', // arrowclosed
    },
    width: 2,
    color: '',
    hidden: false, // 是否隐藏
    // className: '',
    // style: { stroke: 'none' },
    // labelBgPadding: [8, 4],
    // labelBgBorderRadius: 4,
    // labelBgStyle: { fill: '#FFCC00', color: '#fff', fillOpacity: 0.7 },
  },

  /**
   * Background 属性
   * https://reactflow.dev/docs/api/plugin-components/background/#prop-types
   */
  backgroundProps: {
    'color': '#81818a', // variant 图案颜色
    'variant': 'dots', // 'lines' | 'dots' | 'cross'
    'gap': 25,
    'size': 1,
    'lineWidth': 1,
    'offset': 2,
    'style': {
      // 'rgba(26,32,44, .8)', // dark
      'backgroundColor': 'rgba(243,244,244,0.8)',
    },
  },
};

// 1 createContext
export const FlowContext = createContext(initState);

export const FlowContextProvider: React.FC = (props: any) => {
  const {
    children,
    backgroundProps,
  } = props;

  const defaultState = merge({}, initState, {
    backgroundProps
  });

  // 2 Provider
  const value = useRef(proxy(defaultState)).current;
  // console.log('Provider', value, props);

  return (
    <FlowContext.Provider value={value}>
      {children}
    </FlowContext.Provider>
  );
};

// 3 useContext
export const useFlowContext = () => useContext(FlowContext);
